package com.hospital.register.core.controller.api;

import com.hospital.register.common.result.Result;
import com.hospital.register.core.service.HospitalService;
import com.hospital.register.core.service.HospitalSetService;
import com.hospital.register.dto.base.ApiBaseDto;
import com.hospital.register.dto.core.api.HospitalSaveDto;
import com.hospital.register.model.core.Hospital;
import com.hospital.register.validation.groups.InsertValidation;
import com.hospital.register.vo.core.common.HospitalQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/hosp")
@Validated
@Api(tags = "医院api", description = "面向医院")
//@CrossOrigin
public class HospitalApiController {

    /**
     * 处理医院相关业务
     */
    @Autowired
    private HospitalService hospitalService;

    /**
     * 处理医院设置相关业务
     */
    @Autowired
    private HospitalSetService hospitalSetService;

    @ApiOperation(value = "保存医院信息")
    @PostMapping("/saveHospital")
    public Result saveHosp(@Validated(value = InsertValidation.class) HospitalSaveDto dto, @ApiIgnore HttpServletRequest request) {
        this.hospitalSetService.checkSignKey(dto.getHoscode(), dto.getSign(), request);//验签
        dto.setLogoData(dto.getLogoData().replaceAll(" ", "+"));//将logo中的空格替换为加号

        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(dto, hospital);

        if (this.hospitalService.existsByHoscode(dto.getHoscode())) {//医院存在
            this.hospitalService.updateByHoscode(hospital);
        } else {
            this.hospitalService.insert(hospital);
        }

        return Result.ok();
    }

    @ApiOperation(value = "根据编号查询医院")
    @PostMapping("/hospital/show")
    public Result<HospitalQueryVo> showHospital(@Validated ApiBaseDto dto,
                                                @ApiIgnore HttpServletRequest request) {
        this.hospitalSetService.checkSignKey(dto.getHoscode(), dto.getSign(), request);//验签
        HospitalQueryVo vo = this.hospitalService.findByHoscode(dto.getHoscode());
        return Result.ok(vo);
    }

}
